<template>
  <!-- 操作工具栏 -->
  <div class="q-mb-md">
    <!-- <q-btn
      color="primary"
      icon="add"
      label="新增"
      @click="openDialog('create')"
    /> -->
    <q-btn
      color="secondary"
      icon="refresh"
      label="刷新"
      class="q-ml-sm"
      @click="fetchData"
    />
  </div>

  <!-- 数据表格 -->
  <q-table
    :rows="items"
    :columns="columns"
    row-key="id"
  >
    <template #body-cell-image="props">
      <q-td :props="props">
        <q-img
          :src="props.value"
          style="width: 80px; height: 80px"
          spinner-color="primary"
          class="cursor-pointer"
          @click="openImageViewer(props.value)"
        />
      </q-td>
    </template>

    <!-- <template #body-cell-actions="props">
      <q-td
        v-if="String(myId) === String(props.row.user)"
        :props="props"
        class="q-gutter-x-sm"
      >
        <q-btn
          icon="edit"
          color="blue"
          dense
          @click="openDialog('edit', props.row)"
        />
        <q-btn
          icon="delete"
          color="negative"
          dense
          :loading="isLoading && deletingId === props.row.id"
          @click="confirmDelete(props.row.id)"
        />
      </q-td>
      <div v-else>
        {{ ownerData }}
      </div>
    </template> -->
  </q-table>
  <!-- 大图查看对话框 -->
  <q-dialog
    v-model="showImageViewer"
    maximized
  >
    <q-card>
      <q-card-section class="row items-center q-pb-none">
        <q-space />
        <q-btn
          v-close-popup
          icon="close"
          flat
          round
          dense
        />
      </q-card-section>

      <q-card-section
        horizontal
        class="justify-center items-center content-center"
      >
        <q-img
          :src="currentImage"
          contain
          position="center"
          style="max-width: 100vw; max-height: 100vh;"
          @click="showImageViewer = false"
        />
      </q-card-section>
    </q-card>
  </q-dialog>
  <!-- 新增/编辑弹窗 -->
  <q-dialog v-model="showDialog">
    <q-card style="width: 600px; max-width: 80vw;">
      <q-card-section>
        <div class="text-h6">
          {{ isEditMode ? '编辑' : '新增' }}条目
        </div>
      </q-card-section>
      <q-card-section class="q-pt-none">
        <q-form @submit="submitForm">
          <!-- 图片上传区域 -->
          <div class="q-mb-md">
            <div
              class="upload-area relative-position"
              @click="triggerFileInput"
            >
              <q-img
                v-if="myForm.preview"
                :src="myForm.preview"
                style="width: 100%; height: 200px"
                class="rounded-borders"
              >
                <div class="absolute-full overlay flex flex-center">
                  <q-icon
                    name="edit"
                    size="24px"
                    color="white"
                  />
                </div>
              </q-img>

              <div
                v-else
                class="empty-area flex flex-center column"
              >
                <q-icon
                  name="add_photo_alternate"
                  size="48px"
                />
                <div class="q-mt-sm">
                  点击上传图片
                </div>
              </div>

              <input
                ref="fileInput"
                type="file"
                accept="image/*"
                hidden
                @change="handleFileSelect"
              >
            </div>

            <div
              v-if="uploadProgress > 0"
              class="q-mt-sm"
            >
              <q-linear-progress :value="uploadProgress" />
              <div class="text-caption text-center q-mt-xs">
                上传中... {{ Math.round(uploadProgress * 100) }}%
              </div>
            </div>
          </div>

          <!-- 内容 -->
          <q-input
            v-model="myForm.content"
            label="备注"
            outlined
            type="textarea"
            class="q-mb-md"
          />

          <div class="row justify-end q-gutter-sm">
            <q-btn
              v-close-popup
              label="取消"
              color="grey"
            />
            <q-btn
              type="submit"
              label="提交"
              color="primary"
              :disable="isUploading"
            />
          </div>
        </q-form>
      </q-card-section>
    </q-card>
  </q-dialog>

  <!-- 删除确认对话框 -->
  <q-dialog v-model="showDeleteDialog">
    <q-card>
      <q-card-section>
        <div class="text-h6">
          确认删除？
        </div>
      </q-card-section>

      <q-card-actions align="right">
        <q-btn
          v-close-popup
          flat
          label="取消"
          color="primary"
        />
        <q-btn
          flat
          label="确认"
          color="negative"
          @click="deleteItem"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script>
import { defineComponent, ref, onMounted } from 'vue';
import { useQuasar } from 'quasar';
import { useAuthStore } from 'src/stores/auth.js';
import qrcode from 'src/api/qrcode.js';

export default defineComponent({
  name: 'ImageView',
  setup() {
    const $q = useQuasar();
    const auth = useAuthStore();
    const myId = ref(0);
    const myData = ref(auth.getUser());
    const ownerData = ref('别人数据，不可改');
    // 表格数据
    const columns = [
      { name: 'image', label: '图片', field: 'image' },
      { name: 'actions', label: '拥有者', align: 'user' },
      { name: 'content', label: '备注', field: 'content' },
      {
        name: 'id', label: 'ID', field: 'id', align: 'left',
      },
      { name: 'create_datetime', label: '创建时间', field: 'create_datetime' },
    ];

    // 在初始数据中添加模拟数据以便测试
    const items = ref([
      {
        id: 1,
        create_datetime: '2025-03-31T01:46:27.866543',
        update_datetime: '2025-03-31T02:01:02.615361',
        deleted: false,
        delete_datetime: null,
        image: '/media/images/qrcode/a18afc9c39444c37b6295b56492ccf62.png',
        content: '',
        creator: null,
        modifier: null,
        user: 3,
      },
    ]);
    // 对话框状态
    const showImageViewer = ref(false);
    const currentImage = ref('');

    // 方法：打开图片查看器
    const openImageViewer = (imageUrl) => {
      currentImage.value = imageUrl;
      showImageViewer.value = true;
    };
    const isLoading = ref(false);
    // 页面加载时请求数据
    const fetchData = async () => {
      isLoading.value = true;
      const friend = auth.getFriend();
      myId.value = auth.getUser().id;
      // console.log('friend', friend);
      if (friend) {
        myData.value = friend;
      }
      ownerData.value = `${myData.value.nickname || myData.value.nickname}(${myData.value.username})`;
      try {
        const response = await qrcode.getImageByUser(myData.value.id);

        // console.log('fetchData', response.data);

        if (response.status === 200) {
          items.value = response.data.data;
        }
      } catch (error) {
        $q.notify({ type: 'negative', message: '数据加载失败' });
        // console.error('数据加载失败:', error);
      } finally {
        isLoading.value = false;
      }
    };
    // 在组件挂载时调用 fetchData
    onMounted(() => {
      fetchData();
    });

    // 表单相关状态
    const myForm = ref({
      user: myData.value.id,
      image: null,
      content: '',
      preview: '',
    });

    // 上传相关状态
    const fileInput = ref(null);
    const isUploading = ref(false);
    const uploadProgress = ref(0);

    // 对话框状态
    const showDialog = ref(false);
    const isEditMode = ref(false);
    const currentId = ref(null);

    // 删除相关状态
    const showDeleteDialog = ref(false);
    const deletingId = ref(null);

    // 文件上传处理
    // const mockUploadFile = () => {
    //   return new Promise((resolve) => {
    //     const interval = setInterval(() => {
    //       uploadProgress.value += 0.1;
    //       if (uploadProgress.value >= 1) {
    //         clearInterval(interval);
    //         resolve('https://example.com/uploaded-image.jpg');
    //       }
    //     }, 200);
    //   });
    // };

    const triggerFileInput = () => {
      fileInput.value.click();
    };

    const handleFileSelect = async (event) => {
      const file = event.target.files[0];
      if (!file) return;

      // 文件验证
      if (!file.type.startsWith('image/')) {
        $q.notify({ type: 'negative', message: '请选择图片文件' });
        return;
      }
      if (file.size > 20 * 1024 * 1024) {
        $q.notify({ type: 'negative', message: '图片大小不能超过20MB' });
        return;
      }

      myForm.value.image = file;

      // console.log(file);
      // console.log(myForm.value.image);

      // 预览图片
      const reader = new FileReader();
      reader.onload = (e) => {
        myForm.value.preview = e.target.result;
      };
      reader.readAsDataURL(file);
    };

    const openDialog = (mode, row) => {
      isEditMode.value = mode === 'edit';
      if (isEditMode.value) {
        // 编辑模式，加载当前行数据
        myForm.value = { ...row };
        currentId.value = row.id;
        myForm.value.preview = row.image;
      } else {
        // 限制2-3条
        // if (items.value.length >= 3) {
        //   $q.notify({ type: 'negative', message: `新增限制 3 条 ${Math.random()}` });
        //   return;
        // }
        // 新增模式，清空表单
        myForm.value = {
          image: null, content: '', preview: '',
        };
        currentId.value = null;
      }
      showDialog.value = true;
    };

    const submitForm = async () => {
      try {
        isUploading.value = true;
        uploadProgress.value = 0;
        myId.value = auth.getUser().id;

        // 创建 FormData 对象
        const data = new FormData();
        data.append('content', myForm.value.content);
        data.append('user', myId.value);

        let response;

        if (isEditMode.value) {
          if (myId.value !== myForm.value.user) {
            $q.notify({ type: 'negative', message: '非本人二维码' });
            return;
          }
          if (myForm.value.image instanceof File) {
            data.append('image', myForm.value.image);
          }
          // 编辑模式：调用更新接口
          response = await qrcode.updateImage(currentId.value, data);
        } else {
          // 表单验证
          if (!myForm.value.image || !(myForm.value.image instanceof File)) {
            $q.notify({ type: 'negative', message: '请上传图片' });
            return;
          }
          data.append('image', myForm.value.image);
          // 新增模式：调用创建接口
          response = await qrcode.createImage(data);
        }

        if (response.status === 201 || response.status === 200) {
          $q.notify({ type: 'positive', message: `${isEditMode.value ? '编辑' : '新增'}成功` });
          fetchData(); // 刷新表格数据
          showDialog.value = false; // 关闭对话框
        } else {
          $q.notify({ type: 'negative', message: `${isEditMode.value ? '编辑' : '新增'}失败 ${response.status} ${response.data}` });
        }
      } catch (error) {
        $q.notify({ type: 'negative', message: `${isEditMode.value ? '编辑' : '新增'}失败` });
      } finally {
        isUploading.value = false;
        uploadProgress.value = 0;
      }
    };
    // 确认删除
    const confirmDelete = (id) => {
      deletingId.value = id;
      showDeleteDialog.value = true;
    };
    // 删除条目
    const deleteItem = async () => {
      try {
        const response = await qrcode.deleteImage(deletingId.value);
        if (response.status === 204 || response.status === 200) {
          items.value = items.value.filter((item) => item.id !== deletingId.value);
          $q.notify({ type: 'positive', message: '删除成功' });
        } else {
          $q.notify({ type: 'negative', message: `删除失败 ${response.status}` });
        }
      } catch (error) {
        $q.notify({ type: 'negative', message: '删除失败，请稍后再试' });
        // console.error('删除失败:', error);
      } finally {
        showDeleteDialog.value = false;
      }
    };

    return {
      columns,
      items,
      myForm,
      fileInput,
      isUploading,
      uploadProgress,
      showDialog,
      isEditMode,
      showDeleteDialog,
      triggerFileInput,
      handleFileSelect,
      openDialog,
      submitForm,
      confirmDelete,
      deleteItem,
      isLoading,
      showImageViewer, // 添加新的对话框状态
      currentImage, // 当前查看的大图URL
      openImageViewer, // 打开图片查看器的方法
      fetchData,
      deletingId,
      myData,
      myId,
      ownerData,
    };
  },
  watch: {
    'auth.getFriend()': function () {
      this.fetchData();
    },
  },
  mounted() {
    this.fetchData();
  },
});
</script>

<style scoped>
.upload-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  cursor: pointer;
  min-height: 200px;
  overflow: hidden;
}

.upload-area:hover {
  border-color: var(--q-primary);
}

.overlay {
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
}

.upload-area:hover .overlay {
  opacity: 1;
}

.empty-area {
  height: 200px;
  color: #666;
}

.row {
  margin-bottom: 20px;
}

.q-avatar img {
  object-fit: cover;
}

.text-h6 {
  font-weight: bold;
  color: #333;
}

.my-divider {
  border: none;
  height: 1px;
  background-color: #ccc;
  /* 分割线颜色 */
  margin: 20px 0;
  /* 上下外边距 */
}

.search-input {
  width: 100%;
}

.search-results {
  max-height: 400px;
  overflow-y: auto;
  margin-top: 8px;
  border: 1px solid rgba(0, 0, 0, 0.12);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
